package 树.层级遍历;

import 树.递归.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class 二叉树的层平均值_637 {
    List<Double> list = new ArrayList<>();

    public List<Double> averageOfLevels(TreeNode root) {

        /*
        因为题目说是非空，所以不用判断
        if(root==null){
            return null;
        }
        */
        Queue<TreeNode> queue = new LinkedList<>();

        queue.offer(root);
        while (!queue.isEmpty()) {
            double sum = 0.00;
            int count = queue.size();//记录这一层有几个节点
            for (int i = 0; i < count; i++) {
                TreeNode cur = queue.poll();
                sum += cur.val;//求出当前层的和

                //去寻找下一层
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }

            double res = sum / count;
            list.add(res);


        }
        return list;
    }
}
